import { useState, useEffect } from "react";

import { useLocation, useNavigate } from "react-router-dom";

import { accessTokenValidate } from "@/api/jump";
import Header from "@/components/header";
import { needAuthentication } from "../../api/home";
import { getCanQrCode } from "@/api/authentication";

import "./index.less";
import { useLocalStorageState, useRequest } from "ahooks";
import { LOCAL_APP_INFO } from "../../utils/const";
import CustomModal from "../../components/customModal";
import { umscbsBillCreatMemberRequest } from "../../api/jump";

// const token =
//   "QaIc9nWX6XhxT9z1VL6KFnwfoKzgdjnRbfdnL1J2fFP9eyiwzyaE19Uh7LuyxJeDMBt%2BgvX24sximXpxCGlrWYVKVMnuBQD23ZKeXsLf8Xfq%2FN1uamIUJJ%2FokHegOue7WebMQvoO0tAkQcclZwk7v%2FhhTDZJ7iEzXI5PY3E6%2Fsg%3D";
const token = "test";

function Jump() {
  const navigate = useNavigate();
  const location = useLocation();
  const params = new URLSearchParams(location.search);
  const [countdown, setCountdown] = useState(3);
  const [_, setAppInfoData] = useLocalStorageState(LOCAL_APP_INFO, {
    defaultValue: null,
  });
  const [successVisible, setSuccessVisible] = useState(false);

  const { run, cancel } = useRequest(getCanQrCode, {
    manual: true,
    pollingInterval: 2000,
    pollingErrorRetryCount: 60,
    onSuccess: (res) => {
      if (res?.data) {
        setSuccessVisible(false);
        cancel();
        navigate("/paycode", { replace: true });
      } else {
        setSuccessVisible(true);
      }
    },
  });

  useEffect(() => {
    const handleValidate = () => {
      setAppInfoData({});
      const newToken = params.get("mark") || token;
      accessTokenValidate({ token: newToken }).then((res) => {
        const data = {
          token: newToken,
          ...res,
        };
        setAppInfoData(data);
        getParams(data);
      });
    };

    handleValidate();
  }, [navigate]);

  const getParams = (data, timer) => {
    if (Object.keys(data).length > 1) {
      needAuthentication(data).then((res) => {
        const needAuth = res?.data?.needAuth;
        // 1实名认证 2 创建凭证 3 轮训粘码
        handlecheck(needAuth);
      });
    }
  };

  const handlecheck = (needAuth) => {
    if (needAuth == 1) {
      onSetInterval(() => {
        navigate("/home");
      });
    }
    if (needAuth == 2) {
      onUmscbsBillCreatMemberRequest();
    }

    if (needAuth == 3) {
      onSetInterval(() => {
        navigate("/paycode", { replace: true });
      });
    }
  };

  const onSetInterval = (callback) => {
    const timer = setInterval(() => {
      setCountdown((prev) => {
        if (prev <= 1) {
          clearInterval(timer);
          callback();
          return 0;
        }
        return prev - 1;
      });
    }, 1000);
  };

  const onUmscbsBillCreatMemberRequest = () => {
    umscbsBillCreatMemberRequest().then((res) => {
      console.log(res, "res232323");
      onSetInterval(() => {
        run()
      });
    })
  };

  return (
    <div className="jump-page">
      <Header />
      <div className="jump-content">
        <div className="jump-card">
          <div className="jump-icon">
            <div className="loading-spinner"></div>
          </div>
          <div className="jump-title">正在检查安全性</div>
          <div className="jump-message">
            为帮您享受优惠，即将跳转至第三方平台，跳转过程安全，请您耐心等待。
          </div>
          <div className="countdown-section">
            <div className="countdown-text">
              <span className="countdown-number">{countdown}</span>
              <span className="countdown-unit">秒后自动跳转</span>
            </div>
            <div className="countdown-target">跳转到首页</div>
          </div>
          {/* <div className="jump-actions">
            <Button className="jump-btn" block onClick={handleJumpNow}>
              立即跳转
            </Button>
          </div> */}
        </div>
      </div>

      <CustomModal
        visible={successVisible}
        position={"center"}
        mode={"confirm"}
        title="实名认证成功"
        message="请稍等，正在为您跳转亮码页面..."
        footer={false}
      />
    </div>
  );
}

export default Jump;
